package com.example.dictionary.service;

import com.example.dictionary.repository.RocksDbRepository;
import com.example.dictionary.util.KryoSerializer;
import com.example.memento.model.DomainWord;
import com.example.memento.model.ExplanationEntry;
import com.example.memento.model.WordModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * RocksDB 词典委托实现类
 * 使用 Kryo 序列化存储 WordModel
 */
@Service("rocksDBDictionaryDelegate")
public class RocksDBDictionaryDelegate implements DictionaryDelegate {
    
    private static final Logger log = LoggerFactory.getLogger(RocksDBDictionaryDelegate.class);
    
    // Key 前缀
    private static final String WORD_KEY_PREFIX = "";
    
    private final RocksDbRepository rocksDbRepository;
    
    public RocksDBDictionaryDelegate(RocksDbRepository rocksDbRepository) {
        this.rocksDbRepository = rocksDbRepository;
    }
    
    @PostConstruct
    public void init() {
        log.info("RocksDBDictionaryDelegate 初始化完成");
    }
    
    /**
     * 构建存储键
     */
    private String buildKey(String wordName) {
        return WORD_KEY_PREFIX + wordName.toLowerCase().trim();
    }
    
    @Override
    public Optional<WordModel> findWord(String wordName) {
        if (wordName == null || wordName.trim().isEmpty()) {
            return Optional.empty();
        }
        
        String key = buildKey(wordName);
        
        try {
            // 从 RocksDB 读取字节数组
            byte[] data = rocksDbRepository.getBytes(key)
                    .orElse(null);
            
            if (data == null || data.length == 0) {
                return Optional.empty();
            }
            
            // 使用 Kryo 反序列化
            WordModel wordModel = KryoSerializer.deserialize(data, WordModel.class);
            
            if (wordModel != null && wordModel.hasContent()) {
                // log.debug("从 RocksDB 读取词汇: {}", wordName);
                return Optional.of(wordModel);
            }
            
            return Optional.empty();
        } catch (Exception e) {
            log.error("从 RocksDB 读取词汇失败: {}", wordName, e);
            return Optional.empty();
        }
    }
    
    @Override
    public WordModel saveWord(WordModel wordModel) {
        if (wordModel == null) {
            throw new IllegalArgumentException("词汇对象不能为空");
        }
        
        // 确保主词名不为空
        if (wordModel.getPrimaryWord() == null || wordModel.getPrimaryWord().trim().isEmpty()) {
            // 尝试从完整词名列表中获取第一个
            if (wordModel.getFullWordNames() != null && !wordModel.getFullWordNames().isEmpty()) {
                wordModel.setPrimaryWord(wordModel.getFullWordNames().get(0));
            } else {
                throw new IllegalArgumentException("词汇对象必须有主词名或完整词名");
            }
        }
        
        String primaryWord = wordModel.getPrimaryWord().trim();
        String key = buildKey(primaryWord);
        
        try {
            // 更新时间戳
            wordModel.onUpdate();
            
            // 使用 Kryo 序列化
            byte[] data = KryoSerializer.serialize(wordModel);
            
            // 存储到 RocksDB（直接存储字节数组）
            rocksDbRepository.putBytes(key, data);
            
            // log.debug("保存词汇到 RocksDB: {} (大小: {} bytes)", primaryWord, data.length);
            
            return wordModel;
        } catch (Exception e) {
            log.error("保存词汇到 RocksDB 失败: {}", primaryWord, e);
            throw new RuntimeException("保存词汇失败", e);
        }
    }
    
    @Override
    public boolean existsWord(String wordName) {
        if (wordName == null || wordName.trim().isEmpty()) {
            return false;
        }
        
        String key = buildKey(wordName);
        return rocksDbRepository.exists(key);
    }
    
    /**
     * 获取所有词汇的键
     */
    public List<String> getAllWordKeys() {
        try {
            List<String> allKeys = rocksDbRepository.getAllKeys();
            return allKeys.stream()
                    .filter(key -> key.startsWith(WORD_KEY_PREFIX))
                    .map(key -> key.substring(WORD_KEY_PREFIX.length()))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            log.error("获取所有词汇键失败", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 删除词汇
     */
    public void deleteWord(String wordName) {
        if (wordName == null || wordName.trim().isEmpty()) {
            return;
        }
        
        String key = buildKey(wordName);
        try {
            rocksDbRepository.delete(key);
            log.debug("从 RocksDB 删除词汇: {}", wordName);
        } catch (Exception e) {
            log.error("删除词汇失败: {}", wordName, e);
            throw new RuntimeException("删除词汇失败", e);
        }
    }
    
    /**
     * 批量保存词汇
     */
    public void saveWords(List<WordModel> wordModels) {
        if (wordModels == null || wordModels.isEmpty()) {
            return;
        }
        
        int successCount = 0;
        for (WordModel wordModel : wordModels) {
            try {
                saveWord(wordModel);
                successCount++;
            } catch (Exception e) {
                log.warn("批量保存词汇失败: {}", wordModel.getPrimaryWord(), e);
            }
        }
        
        log.info("批量保存词汇完成: {}/{}", successCount, wordModels.size());
    }
}

